/**
 * @file 用户管理
 * @date 2025/09/01 16:36:17
 * @author lyqjob@yeah.net
 */

import {  useState, useEffect  } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, Select, Col, Row, message, Cascader } from 'antd';
import AuthButton from '@/components/AuthButton';
import { adminApi } from "@/services/admin";
import dayjs from '@/utils/dayjs.js';
import { useSelector } from 'react-redux';



const Userlist = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [form] = Form.useForm();
    const [formValues, setFormValues] = useState();
    const [open, setOpen] = useState(false);
    const [departmentList, setDepartmentList] = useState([]);
    const [roleList, setRoleList] = useState([]);
    const [pageSize, setPageSize] = useState(10)
    const [current, setCurrent] = useState(1)
    const [total, setTotal] = useState(0)
    const [selectedRowKeys, setSelectedRowKeys] = useState([])
    const [options, setOptions] = useState([]);
    const [address, setAddress] = useState(''); // 中文地址(省/市/区)
    const [address_ids, setAddress_ids] = useState('');// 用户地址id字符串（逗号分隔）1,2,3
    const userInfo = useSelector(state => state.global.userInfo)

    const columns = [
        { title: '用户编号', dataIndex: 'code', key: '', width: 150, fixed: 'left' },
        { title: '用户名', dataIndex: 'username', key: '', width: 150 },

        {
            title: '姓名',
            dataIndex: 'name',
            key: '',
            width: 150,
        },
        {
            title: '性别', dataIndex: 'gender', key: '', width: 150,
            render: (text) => text === 1 ? '男' : text === 0 ? '女' : '未知'
        },
        { title: '部门', dataIndex: 'department_name', key: '', ellipsis: true, width: 150 },
        { title: '手机号', dataIndex: 'phone', key: '', width: 150 },
        { title: '邮箱', dataIndex: 'email', key: '', width: 150 },
        {
            title: '家庭地址',
            dataIndex: 'address',
            key: '',
            width: 250,
            render: (text, item) => item.address + '/' + item.detail_address

        },

        {
            title: '状态', dataIndex: 'status', key: '',
            width: 150,
            render: (tag) => {
                return (
                    <Tag color={tag === 0 ? 'green' : 'red'} key={tag}>
                        {tag === 0 ? '正常' : '停用'}
                    </Tag>
                )
            }
        },
        {
            title: '创建时间', dataIndex: 'created_at', key: '', width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        { title: '创建人', dataIndex: 'create_by_name', key: '', width: 150 },
        {
            title: '更新时间', dataIndex: 'updated_at', key: '', width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        { title: '修改人', dataIndex: 'update_by_name', key: '', width: 150 },
        {
            title: '操作',
            dataIndex: '',
            key: 'options',
            fixed: 'right',
            width: 250,
            render: (item) => {
                return (
                    <Space >
                        {
                            item.is_protected === 0 ?
                                <AuthButton permission={['user:batch:delete']}>
                                    <a onClick={() => deleteUser(item.id)}>删除</a>
                                </AuthButton> : null
                        }
                        {
                            item.is_protected === 0 ?
                                <AuthButton permission={['user:update']}>
                                    <a onClick={() => { editUser(item) }}>编辑</a>
                                </AuthButton> : null
                        }


                        {
                            item.is_protected === 0 && userInfo?.is_admin ?
                                <AuthButton permission={['user:reset:password']}>
                                    <a onClick={() => { resetPassword(item.id) }}>重置密码</a>
                                </AuthButton>
                                : null
                        }
                    </Space>
                )
            }

        },
    ];


    useEffect(() => {
        getList(current, pageSize)
        getDepartmentList()
        getProvinceList()
        getRoleList()
    }, [current, pageSize])

    // 重置密码
    const resetPassword = async (id) => {
        const [err, res] = await adminApi.resetPassword(id)
        if (err) {
            // message.warning('重置密码失败')
        }
        if (res.code === 200) {
            message.success(`重置密码成功,新密码为:${res.data.newpassword}`, 3)
            getList(current, pageSize)
        }
    }

    // 删除用户
    const deleteUser = async (id) => {
        const [err, res] = await adminApi.deleteUser(id)
        if (err) {
            // message.warning('删除失败')
        }
        if (res.code === 200) {
            message.success('删除成功')
            getList(current, pageSize)
        }
    }

    // 地址数据转换Antd  组件需要的格式
    const convertToAntdOptions = (data, isLeaf = false, level = 0) => {
        return data.map((item, index) => ({
            label: item.name,
            value: item.id,
            isLeaf: isLeaf,
            level: level,
            index: index
        }));
    };

    // 获取部门列表
    const getDepartmentList = async () => {
        const [err, res] = await adminApi.getAllDepartment({ current: 1, pageSize: 1000 })
        if (err) {
            message.warning('获取部门列表失败')
        }
        if (res.code === 200 && res?.data?.data) {
            const list = res.data.data.filter(item => item.type === 1);
            setDepartmentList(list)
        }
    }

    // 获取省份列表
    const getProvinceList = async () => {
        const [err, res] = await adminApi.getProvinceList()
        if (err) {
            // message.warning('获取省份列表失败')
        }
        if (res.code === 200 && res?.data) {
            const list = convertToAntdOptions(res.data)
            setOptions(list)
        }
    }

    // 获取城市列表
    const getCityList = async (provinceId) => {
        const [err, res] = await adminApi.getCityList(provinceId)
        if (err) {
            // message.warning('获取城市列表失败')
            return []
        }
        if (res.code === 200 && res?.data) {
            const list = convertToAntdOptions(res.data, false, 1)
            return list;
        }
    }

    // 获取区县列表
    const getDistrictList = async (cityId) => {
        const [err, res] = await adminApi.getDistrictList(cityId)
        if (err) {
            // message.warning('获取区县列表失败')
            return []
        }
        if (res.code === 200 && res?.data) {
            const list = convertToAntdOptions(res.data, true, 2)
            return list;
        }
    }

    const onChange = (value, selectedOptions) => {
        const address_ids = value.join(',')
        setAddress_ids(address_ids)
        const address = selectedOptions.map(item => item.label).join('/')
        setAddress(address)
    };

    // 加载子数据
    const loadData = async selectedOptions => {
        const targetOption = selectedOptions[selectedOptions.length - 1];

        const id = targetOption.value;
        if (targetOption.level === 0) {
            const cityData = await getCityList(id);
            targetOption.children = cityData
        }
        if (targetOption.level === 1) {
            const districtData = await getDistrictList(id);
            targetOption.children = districtData
        }

        setOptions([...options]);

    };

    // 获取用户列表
    const getList = async (page, limit) => {
        setLoading(true);
        const [err, res] = await adminApi.getAlluser({ page, limit });
        if (err) {
            setLoading(false);
            return;
        }
        if (res.code === 200 && res?.data?.data) {
            setData(res.data.data)
            setTotal(res.data.pagination.total)
        }
        setLoading(false);
    }

    // 获取角色列表
    const getRoleList = async () => {
        const [err, res] = await adminApi.getAllrole({ current: 1, pageSize: 1000 })
        if (err) {
            // message.warning('获取角色列表失败')
        }
        if (res.code === 200 && res?.data?.data) {
            setRoleList(res.data?.data)
        }
    }

    // 编辑用户
    const editUser = (item) => {
        setFormValues(item)
        form.setFieldsValue({
            ...item,
            department_id: item.department_id,
            roleIds: item.role_ids
        })
        setOpen(true)
    }

    // 提交表单
    const onCreate = async values => {

        // 新增
        values.address_ids = address_ids;
        values.address = address;

        // 编辑时，需要传递id
        if (formValues?.id) {
            values.id = formValues.id;

            const [err, res] = await adminApi.updateUser(values)
            if (err) {
                // message.warning('添加失败')
                // setOpen(false)
            }
            if (res) {
                message.success('更新成功')
                setFormValues()
                form.resetFields()
                setOpen(false)
                getList(current, pageSize)
            }
            return
        }


        // 新增
        const [err, res] = await adminApi.createUser(values)
        if (err) {
            // message.warning('添加失败')
            // setOpen(false)
        }
        if (res) {
            message.success('添加成功')
            form.resetFields()
            setOpen(false)
            getList(current, pageSize)
        }

    };

    // 分页
    const rowSelection = {
        onChange: (newSelectedRowKeys, _selectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
        getCheckboxProps: record => ({
            disabled: record.name === '超级管理员', // Column configuration not to be checked
        }),
    };

    // 批量删除用户
    const batchDeleteUser = async (values) => {
        if (values.length === 0) {
            message.warning('请选择要删除的用户')
            return
        }

        const [err, res] = await adminApi.batchDeleteUser({ ids: values })
        if (err) {
            // message.warning('删除失败')
        }
        if (res) {
            message.success('删除成功')
            getList(current, pageSize)
        }

    };

    return (
        <div className="container">
            <Space>
                <AuthButton permission={['user:create']}>
                    <Button onClick={() => {
                        setOpen(true)
                        // getRoleList()
                        form.setFieldsValue({
                            roleIds: [5]
                        })
                    }} type="primary" style={{ marginBottom: 16 }}>
                        创建用户
                    </Button>
                </AuthButton>
                <AuthButton permission={['user:batch:delete']}>
                    <Button danger onClick={() => batchDeleteUser(selectedRowKeys)} type="primary" style={{ marginBottom: 16 }}>
                        批量删除
                    </Button>
                </AuthButton>

            </Space>
            <Table
                loading={loading}
                rowKey={'id'}
                columns={columns}
                rowSelection={{ type: 'checkbox', ...rowSelection }}
                dataSource={data}
                scroll={{ x: 1500 }}
                pagination={{
                    pageSize: pageSize,
                    current: current,
                    showPage: true,
                    total: total,
                    showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
                    onChange: (page, pageSize) => {
                        setPageSize(pageSize)
                        setCurrent(page)
                        getList(page, pageSize)
                    }
                }}
            />

            <Modal
                open={open}
                title={formValues?.id ? '编辑用户' : '创建用户'}
                okText="确定"
                cancelText="取消"
                width={800}
                okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
                onCancel={() => {
                    setOpen(false)
                    setFormValues()
                }}

                forceRender
                destroyOnHidden
                modalRender={dom => (
                    <Form
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        layout="horizontal"
                        form={form}
                        name="form_in_modal"
                        initialValues={{ password: '123456', avatar_url: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', gender: 1 }}
                        clearOnDestroy
                        onFinish={values => onCreate(values)}
                        style={{ maxWidth: 800 }}
                    >
                        {dom}
                    </Form>
                )}
            >

                <Form.Item
                    name="avatar_url"
                    label="头像"
                    hidden
                >
                    <Input />
                </Form.Item>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="gender"
                            label="性别"
                            rules={[{ required: true, message: '请选择性别' }]}
                        >
                            <Select>
                                <Select.Option key={1} value={1}>男</Select.Option>
                                <Select.Option key={0} value={0}>女</Select.Option>
                                {/* <Select.Option key={2} value={2}>其他</Select.Option> */}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="username"
                            label="用户名"
                            rules={[{ required: true, message: '请添加用户名' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="name"
                            label="姓名"
                            rules={[{ required: true, message: '请添加姓名' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>

                </Row>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="phone"
                            label="手机号"
                            maxLength={11}
                            rules={[{ required: true, message: '请添加手机号' }]}
                        >
                            <Input type='number' maxLength={11} />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="department_id"
                            label="部门"
                            rules={[{ required: true, message: '请选择部门' }]}
                        >
                            <Select>
                                {
                                    departmentList.map(item => (
                                        <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>

                    {
                        !formValues ? (
                            <Col span={8} >
                                <Form.Item
                                    name="password"
                                    label="密码"
                                    tooltip="初始密码123456"
                                    rules={[{ required: true, message: '请添加密码' }]}

                                >
                                    <Input.Password />
                                </Form.Item>
                            </Col>
                        ) : null
                    }
                </Row>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="email"
                            label="邮箱"
                        // rules={[{ required: true, message: '请添加邮箱' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}
                            name="roleIds"
                            label="绑定角色"
                            rules={[{ required: true, message: '请选择角色' }]}
                        >
                            <Select mode="multiple">
                                {
                                    roleList.map(item => (
                                        <Select.Option key={item.id} value={item.id} disabled={item.is_protected === 1}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>

                </Row>
                <Row>
                    <Col span={16} >
                        <Form.Item
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 21 }}
                            name="address"
                            label="家庭地址"
                        // rules={[{ required: true, message: '请选择地址' }]}
                        >
                            <Cascader options={options} loadData={loadData} onChange={onChange} changeOnSelect />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="detail_address"
                            label="详细地址"
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
            </Modal>
        </div>
    )
}


export default Userlist;
